/**
 * Created by Maxwell on 2016/9/26.
 */

"use strict";
(function ($, doc) {
    FastClick.attach(doc.body);
    $.extend({
        alert: function (opt) {
            if (typeof opt === 'string') {
                layer.msg(opt, {time: 1000});
            } else {
                layer.open(opt);
            }
        }
    });

    // 全局变量
    var common = {
        loadIndex : 0,
        isLoadNextPage:false,
        login: function (params) {
            $.ajax({
                url: 'common/login',
                type: 'post',
                data: {
                    username: params.username,
                    password: params.password
                },
                beforeSend:function(){
                    common.loadIndex = layer.load(2);
                }
            }).done(function (data) {
                if (data.status == 'succeed') {
                    $.alert('登录成功');
                    params.successCallback.apply(null, [data]);
                } else if (data.status == 'hasLogin') {
                    params.successCallback.apply(null, [data]);
                } else {
                    $.alert('账号或密码错误');
                }
            }).fail(function (error) {
                params.errorCallback.apply(null, error);
            }).always(function (){
                layer.close(common.loadIndex);
            });
        }
    };

    $('#login').on('click', function (e) {
        var username = $(this).parents('form').find('input[name="username"]').val();
        var pwd = $(this).parents('form').find('input[name="password"]').val();
        common.login({
            username: $.trim(username),
            password: $.trim(pwd),
            successCallback: function (data) {
                $.cookie('access_token', data.access_token, { path: '/', expires: 0.25 });
                // sessionStorage.setItem('hasLogin',1);
                setTimeout(function(){
                    location.href = 'index';
                },500);
            }
        });
    });
    window.common = common;
})(jQuery, document);


